import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

export function useIframeComm() {
  const isIframe = ref(false)
  const parentOrigin = ref('')

  // 检查当前页面是否在 iframe 中
  const checkIfInIframe = (): boolean => {
    try {
      return window.self !== window.top
    } catch (e) {
      return true
    }
  }

  // 向父窗口发送 URL 变化消息
  const sendUrlChangeToParent = (url: string) => {
    if (!isIframe.value || !parentOrigin.value) return

    window.parent.postMessage({
      type: 'mcp-url-change',
      url: url
    }, parentOrigin.value)
  }

  // 初始化 iframe 通信
  const initIframeComm = (router: ReturnType<typeof useRouter>) => {
    isIframe.value = checkIfInIframe()
    
    if (!isIframe.value) return
    
    // 监听父窗口的消息以获取源
    const handleMessage = (event: MessageEvent) => {
      if (event.data && event.data.type === 'mcphub-parent-ready') {
        parentOrigin.value = event.origin
        // 发送初始 URL
        sendUrlChangeToParent(window.location.href)
      }
    }
    
    window.addEventListener('message', handleMessage)

    // 监听路由变化
    router.afterEach((to) => {
      sendUrlChangeToParent(window.location.href)
    })

    // 当组件卸载时移除事件监听器
    return () => {
      window.removeEventListener('message', handleMessage)
    }
  }

  return {
    isIframe,
    initIframeComm,
    sendUrlChangeToParent
  }
} 